<?php
/**
 * Created by PhpStorm.
 * User: envision
 * Date: 2018-10-08
 * Time: 12:55
 */

namespace App\Http\Controllers\Api\V1\Manager\User;


use App\Http\Controllers\Controller;
use App\Models\Level;
use App\Models\UserHome;
use App\Models\UserStatistics;
use App\Models\VipLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{

    private $namespace = "App\Http\Controllers\Api\V1\Manager\User\UserController";

    public function index(Request $request)
    {
        $userId = $request->userId;
        $userName = $request->userName;
        $userPhone = $request->userPhone;
        $is_suosi_switch = $request->is_suosi_switch;
        $is_zhuxiao_switch = $request->is_zhuxiao_switch;
        $isVip = $request->isVip;
        $pageSize = $request->pageSize;
        $sql = UserHome::select('t1.id', 't2.levelName', 't1.phone', 't1.nickname', 't1.isVip', 't1.use_integral', 't1.add_integral', 't1.spend',
            't1.is_suosi_switch', 't1.is_zhuxiao_switch', 't1.createtime as createTime', 't1.inviteUserNum')
            ->from((new UserHome())->getTable() . ' as t1')
            ->join((new Level())->getTable() . ' as t2', 't1.levelId', '=', 't2.levelId');
        if (isset($userId)) {
            $sql->where('t1.id', $userId);
        }
        if (isset($userName)) {
            $sql->where('t1.nickname', 'like', "%$userName%");
        }
        if (isset($userPhone)) {
            $sql->where('t1.phone', 'like', "%$userPhone%");
        }
        if (isset($is_suosi_switch)) {
            $sql->where('t1.is_suosi_switch', $is_suosi_switch);
        }
        if (isset($is_zhuxiao_switch)) {
            $sql->where('t1.is_zhuxiao_switch', $is_zhuxiao_switch);
        }
        if (isset($isVip)) {
            $sql->where('t1.isVip', $isVip);
        }
        $userList = $sql->orderBy('t1.createtime', 'desc')
            ->paginate($pageSize)->toArray();
        $user['userList'] = $userList['data'];
        foreach ($user['userList'] as $key => $value) {
            $user['userList'][$key]['createTime'] = date("Y-m-d H:i:s", $value['createTime']);
            $vipSpend = VipLog::where('userId', $value['id'])->sum('vipPrice');
            $user['userList'][$key]['spend'] = $vipSpend + $value['spend'];
        }
        $user['totalNum'] = $userList['total'];
        return $this->apiResponse($user);
    }

    public function show(Request $request, $userId)
    {
        $user = UserHome::select('t1.id', 't2.levelName', 't1.phone', 't1.nickname', 't1.isVip', 't1.use_integral', 't1.add_integral', 't1.spend', 't1.spend as vipSpend', 't1.spend as shopSpend',
            't1.is_suosi_switch', 't1.is_zhuxiao_switch', 't1.createtime as createTime', 't1.inviteUserNum')
            ->from((new UserHome())->getTable() . ' as t1')
            ->join((new Level())->getTable() . ' as t2', 't1.levelId', '=', 't2.levelId')
            ->where('id', $userId)
            ->first();
        $user['vipSpend'] = VipLog::where('userId', $userId)->sum('vipPrice');
        $user['spend'] = $user['vipSpend'] + $user['shopSpend'];
        $user['createTime'] = date("Y-m-d H:i:s", $user['createTime']);
        return $this->apiResponse($user);
    }

    public function inviteUserList(Request $request)
    {
        $userId = $request->userId;
        $pageSize = $request->pageSize;
        $sql = UserHome::select('t1.id', 't2.levelName', 't1.phone', 't1.nickname', 't1.isVip', 't1.use_integral', 't1.add_integral', 't1.spend',
            't1.is_suosi_switch', 't1.is_zhuxiao_switch', 't1.createtime as createTime', 't1.inviteUserNum')
            ->from((new UserHome())->getTable() . ' as t1')
            ->join((new Level())->getTable() . ' as t2', 't1.levelId', '=', 't2.levelId')
            ->where('inviteUserId', $userId);

        $userList = $sql->orderBy('t1.createtime', 'desc')
            ->paginate($pageSize)->toArray();
        $user['userList'] = $userList['data'];
        foreach ($user['userList'] as $key => $value) {
            $user['userList'][$key]['createTime'] = date("Y-m-d H:i:s", $value['createTime']);
            $vipSpend = VipLog::where('userId', $value['id'])->sum('vipPrice');
            $user['userList'][$key]['spend'] = $vipSpend + $value['spend'];
        }
        $user['totalNum'] = $userList['total'];
        return $this->apiResponse($user);
    }

    public function vipUserList(Request $request)
    {
        $userId = $request->userId;
        $pageSize = $request->pageSize;
        $sql = VipLog::select('vipLogId','payCode','orderNum','createTime','payType','vipPrice','createTime','endTime')
            ->where('userId', $userId);

        $userList = $sql->orderBy('createtime', 'desc')
            ->paginate($pageSize)->toArray();
        $user['vipList'] = $userList['data'];
        $user['totalNum'] = $userList['total'];
        return $this->apiResponse($user);
    }

    public function update(Request $request, $userId)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $user = UserHome::where('id', $userId)->first();
        if ($user['is_suosi_switch']) {
            $content = "禁用";
            UserHome::where('id', $userId)->update(['is_suosi_switch' => 0]);
        } else {
            $content = "启用";
            UserHome::where('id', $userId)->update(['is_suosi_switch' => 1]);
        }
        //添加管理员日志开始
        $url = $this->namespace . "/update";
        $title = "修改";
        $content .= "了id为【".$userId."】的用户";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "用户模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function statisticsIndex(Request $request)
    {
        $user = [];
        $user['userNum'] = UserHome::count();
        $user['ptUserNum'] = UserHome::where('isVip', 0)->count();
        $user['vipUserNum'] = UserHome::where('isVip', 1)->count();
        return $this->apiResponse($user);
    }

    public function statisticsMonth(Request $request)
    {
        $month = $request->month ?: date("Y-m");
        $type = $request->type ?: 1;
        $userStatisticsList = UserStatistics::where('createDay', 'like', "%$month%")->where('type', $type)->orderBy("createDay", 'asc')->get()->toArray();
        $startDay = $month . "-01";
        $statisticsList = [];
        $todayNum = 0;
        $yesterdayNum = 0;
        for ($i = 0; $i <= 40; $i++) {
            if($i != 0){
                $day = date("Y-m-d",strtotime("+$i Day",strtotime($startDay)));
            }else{
                $day = $startDay;
            }
            if(date("Y-m",strtotime($day)) != $month){
                break;
            }
            $statisticsList[$i]['num'] = 0;
            $statisticsList[$i]['time'] = $day;
            foreach ($userStatisticsList as $key=>$value){
                if($value['createDay'] == $day){
                    $statisticsList[$i]['num'] = $value['num'];
                    unset($userStatisticsList[$key]);
                    break;
                }
            }
            if($day == date("Y-m-d")){
                $todayNum = $statisticsList[$i]['num'];
            }
            if($day == date("Y-m-d",strtotime("-1 Day"))){
                $yesterdayNum = $statisticsList[$i]['num'];
            }
        }
        if($yesterdayNum == 0){
            $yesterdayNum = UserStatistics::where('createDay', date("Y-m-d",strtotime('-1 Day')))->where('type', $type)->sum('num');
        }
        $addUserRate = 0;
        $todayUserNum = $todayNum;
        $yesterdayUserNum = $yesterdayNum;
        if ($todayUserNum > $yesterdayUserNum) {
            $userNumDifference = $todayUserNum - $yesterdayUserNum;
            if ($yesterdayUserNum == 0) {
                $addUserRate = intval($userNumDifference * 100);
            } else {
                $addUserRate = intval(($userNumDifference / $yesterdayUserNum) * 100);
            }
        } else if ($todayUserNum < $yesterdayUserNum) {
            $userNumDifference = $yesterdayUserNum - $todayUserNum;
            $addUserRate = -(intval(($userNumDifference / $yesterdayUserNum) * 100));
        }
        $data = [];
        $data['statisticsList'] = $statisticsList;
        $data['todayNum'] = $todayNum;
        $data['yesterdayNum'] = $yesterdayNum;
        $data['addUserRate'] = $addUserRate;
        return $this->apiResponse($data);

    }

}